<template>
  <div>
    <el-dialog :visible.sync="showPointDialog" :before-close="check" title="新增" :modal-append-to-body="false" width="67%">
      <el-card class="box-card">
        <div slot="header">
          <span class="bold">资费策略</span>
        </div>

        <el-row>
          <el-col :span="12">
            <div class="watch required">
              策略名称：
              <el-input
                v-model="tacticsName"
                style="width:200px"
                size="mini"
                placeholder="请输入策略名称"
              />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="watch required">
              策略价格：
              <el-input
                v-model="tacticsPrice"
                style="width:200px"
                size="mini"
                placeholder="请输入策略价格"
              />
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="watch required">自动续订：
              <el-select v-model="isGoon" placeholder="请选择" size="mini" @change="watchauto">
                <el-option value="0" label="是" />
                <el-option value="1" label="否" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="watch required">计费周期：
              <el-input
                v-model="cycle"
                style="width:200px"
                size="mini"
                placeholder="请输入周期数"
              />
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="watch required">计费方式：
              <el-select v-model="selectConditions" placeholder="请选择" size="mini">
                <el-option v-for="item in payStyles" :key="item.typeId" :disabled="item.checked" :value="item.typeId" :label="item.typeName" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="12">
            <div v-show="status" class="watch">退订锁定期：
              <el-input
                v-model="lockPeriod"
                style="width:200px"
                size="mini"
                placeholder="请输入退订锁定期"
              />
            </div>
          </el-col>
        </el-row>

      </el-card>

      <el-card class="box-card1">
        <div slot="header">
          <span class="bold">计费渠道</span>
        </div>
        <!-- <el-button
          type="primary"
          size="mini"
          round
          :disabled="statusBtn"
          @click="addPay"
        >新建</el-button> -->
        <!-- <div v-for="(num, rank) in payArr" :key="rank"> -->
        <div>
          <el-row>
            <el-col :span="24">
              <div class="watch required">计费渠道：
                <el-select
                  v-model="payRealArr"
                  placeholder="请选择"
                  multiple
                  style="width:40%"
                  size="mini"
                >
                  <el-option
                    v-for="data in paySelected"
                    :key="data.billingChannelId"
                    :value="data.billingChannelId"
                    :label="data.billingChannelName"
                  />
                </el-select>
              </div>
            </el-col>
            <!-- <el-col :span="12">
              <div class="watch">计费码：
                <el-input
                  v-model="num.billingCode"
                  style="width:200px"
                  size="mini"
                  disabled
                  placeholder="请输入计费码"
                />
                <el-button
                  type="primary"
                  plain
                  round
                  size="mini"
                  style="display:inline-block;margin-left: 5px;"
                  @click="select(rank, num.billingCode)"
                >选择</el-button>
                <el-button
                  v-show="rank > 0 ? true : false"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deletePay(rank)"
                />
              </div>
            </el-col> -->
          </el-row>
        </div>
      </el-card>
      <div class="btnall">
        <el-button
          type="primary"
          round
          size="small"
          style="width:100px"
          @click="saveResult"
        >保存</el-button>
        <el-button
          type="primary"
          plain
          round
          size="small"
          style="width:100px"
          @click="check"
        >取消</el-button>
      </div>
    </el-dialog>
    <select-pay :select-dialog="selectDialog" :index-num="index" :code-val="codeVal" @closeSelect="closeSelect" />
  </div>
</template>

<script>
import { repeatName, save, getSelectS } from '@/api/expenses.js'
import { mapGetters } from 'vuex'
import selectPay from './selectPay.vue'
import { plus, positive } from '@/utils/validate.js'
export default {
  name: 'Watch',
  components: {
    selectPay: selectPay
  },
  props: {
    // 遮罩层
    addDialog: {
      type: Boolean,
      default: false
    },

    // 支付渠道下拉
    paySelect: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      tacticsName: '', // 策略名称
      payRealArr: [],
      payStyles: [],
      tacticsPrice: '', // 策略价格
      cycle: '', // 计费周期
      selectConditions: '', // 单选计费方式
      isGoon: '', // 是否自动续订
      showPointDialog: false, // 遮罩
      selectDialog: false, // 选择遮罩
      index: 0, // 计费码序号
      id: '', // id
      status: false,
      statusBtn: false, // 按钮是否禁用
      lockPeriod: '',
      platformArr: [],
      paySelected: [], // 下拉选择
      codeVal: '', // 携带选择的值
      /*  payArr: [{ // 计费数组
        billingChannelId: '',
        billingCode: '',
        status: false
      }], */
      payArr: []
      /* payArr: [{ // 计费数组
        billingChannelId: '', // 计费渠道
        billingChannelName: '', // 计费名称
        billingCode: '', // 计费码
        status: false
      }] */
    }
  },
  computed: {
    ...mapGetters(['plat'])
  },
  watch: {
    addDialog(newVal) {
      this.showPointDialog = newVal
      this.paySelected = this.paySelect
      // 初始化
      this.tacticsName = ''
      this.tacticsPrice = ''
      this.cycle = ''
      this.selectConditions = ''
      this.isGoon = ''
      if (newVal) {
        this.loadSelect()
      }
    },
    isGoon(newVal) {
      if (newVal === '0') {
        if (this.selectConditions !== '2' && this.selectConditions !== '3') {
          this.selectConditions = ''
        }
        this.payStyles.forEach(item => {
          if (item.typeId === '2' || item.typeId === '3') {
            item.checked = false
          } else {
            item.checked = true
          }
        })
      } else {
        this.lockPeriod = ''
        this.payStyles.forEach(item => {
          item.checked = false
        })
      }
    }
  },
  methods: {
    // 获取下拉框计费方式
    loadSelect() {
      getSelectS({
        functionType: 'billingMode'
      }).then(res => {
        console.log(res)
        this.payStyles = res.data.list
      })
    },
    // 监听
    watchauto(val) {
      console.log(val)
      if (val === '0') {
        this.status = true
      } else {
        this.status = false
      }
    },
    // 回调父组件
    check(val) {
      this.payRealArr = []
      this.showPointDialog = false
      this.statusBtn = false
      this.status = false
      this.$emit('closeAdd', val)
      // this.payArr.splice(0, this.payArr.length - 1)
      this.paySelect.forEach(item => {
        item.disabled = false
      })
      this.payArr = []
    },

    // 新建
    addPay() {
      for (let i = 0; i < this.payArr.length; i++) {
        if (!this.payArr[i].billingChannelId) {
          this.$message({
            message: '请选择计费渠道',
            type: 'error'
          })
          return
        }
      }

      var len = this.paySelected.length
      var payLen = this.payArr.length
      this.payArr[payLen - 1].status = true
      this.compareSelect()
      // 超出下拉框数量
      if (payLen + 1 === len) {
        this.statusBtn = true
      }
      this.payArr.push({
        billingChannelId: '',
        billingCode: ''
      })
    },

    // 比对可选
    compareSelect() {
      var paySelect = []
      for (let i = 0; i < this.payArr.length; i++) {
        paySelect.push(this.payArr[i].billingChannelId)
      }
      // paySelected
      for (let j = 0; j < this.paySelected.length; j++) {
        for (let k = 0; k < paySelect.length; k++) {
          if (paySelect[k] === this.paySelected[j].billingChannelId) {
            this.paySelected[j].disabled = true
          }
        }
      }
    },

    // 比对可选
    compareSelectCancel(indexArr) {
      for (let j = 0; j < this.paySelected.length; j++) {
        if (indexArr === this.paySelected[j].billingChannelId) {
          this.paySelected[j].disabled = false
        }
      }
    },

    // 比对可选plan B
    compareSelectB() {
      var paySelect = []
      for (let i = 0; i < this.payArr.length; i++) {
        paySelect.push(this.payArr[i].billingChannelId)
      }
      // paySelected
      for (let j = 0; j < this.paySelected.length; j++) {
        for (let k = 0; k < paySelect.length; k++) {
          if (paySelect[k] !== this.paySelected[j].billingChannelId) {
            this.paySelected[j].disabled = false
          } else {
            this.paySelected[j].disabled = true
          }
        }
      }
    },

    // 选择
    select(index, codeVal) {
      this.selectDialog = true
      this.index = index
      this.codeVal = codeVal
    },

    // 关闭选择
    closeSelect(val, rank) {
      // 找到是第几个计费码
      if (val || val === '') {
        this.payArr[rank].billingCode = val
      }
      this.selectDialog = false
    },

    // 删除计费码
    deletePay(index) {
      // 取消最后一个不可选
      if (index === this.payArr.length - 1) {
        this.payArr[index - 1].status = false
      }

      var indexArr = this.payArr[index].billingChannelId
      this.compareSelectCancel(indexArr)
      this.payArr.splice(index, 1)
      this.statusBtn = false
      console.log(this.payArr)
      console.log(this.paySelected)
    },

    // 监听下拉选择
    handle(val, rank) {
      // 获取label，find查找
      // 此处有bug，我服了,暂时解决不了，好气
      // console.log()
      var label = {}
      label = this.paySelected.find((item) => {
        return item.billingChannelId === val
      })
      console.log(val)
      this.payArr[rank].billingChannelName = label.billingChannelName
    },

    // 保存
    saveResult() {
      if (!this.tacticsName) {
        this.$message({
          message: '请输入策略名称',
          type: 'error'
        })
        return
      }

      if (!this.tacticsPrice) {
        this.$message({
          message: '请输入策略价格',
          type: 'error'
        })
        return
      }

      /* if (this.tacticsPrice === '0') {
        this.$message({
          message: '策略价格不能为0',
          type: 'error'
        })
        return
      } */

      if (!this.cycle && this.cycle !== '0') {
        this.$message({
          message: '请输入计费周期',
          type: 'error'
        })
        return
      }

      if (!positive(this.cycle)) {
        this.$message({
          message: '计费周期为正整数',
          type: 'error'
        })
        return
      }

      if (this.isGoon === '0') {
        /* if (!this.lockPeriod) {
          this.$message({
            message: '请输入退订锁定期',
            type: 'error'
          })
          return
        } */
        if (this.lockPeriod !== '' && !positive(this.lockPeriod)) {
          this.$message({
            message: '退订锁定期必须为正整数',
            type: 'error'
          })
          return
        }
      }

      if (this.tacticsPrice !== 0 && !plus(this.tacticsPrice)) {
        this.$message({
          message: '策略价格必须为正数或0',
          type: 'error'
        })
        return
      }

      if (!plus(this.cycle)) {
        this.$message({
          message: '计费周期必须为正数',
          type: 'error'
        })
        return
      }

      /* for (let i = 0; i < this.payArr.length; i++) {
        if (this.payArr[i].billingChannelId === '') {
          this.$message({
            message: '计费渠道至少填写一条',
            type: 'error'
          })
          return
        }
      } */
      if (this.payRealArr.length < 1) {
        this.$message({
          message: '计费渠道至少填写一条',
          type: 'error'
        })
        return
      }
      repeatName({ name: this.tacticsName }).then(res => {
        this.paySelected.forEach(item => {
          this.payRealArr.forEach(val => {
            if (val === item.billingChannelId) {
              this.payArr.push({
                billingChannelId: item.billingChannelId,
                billingChannelName: item.billingChannelName,
                platformId: item.platformId
              })
            }
          })
        })
        if (res.resultCode === '0000') {
          var data = {
            name: this.tacticsName,
            price: this.tacticsPrice,
            mode: this.selectConditions,
            cycle: this.cycle,
            isGoon: this.isGoon,
            billingChannelList: this.payArr,
            lockPeriod: this.lockPeriod
          }
          save(data).then(res => {
            if (res.resultCode === '0000') {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.check(true)
            } else {
              this.payArr = []
              // this.check()
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.box-card{
  margin-top: -25px;
}
.box-card1{
  margin-top: 10px;
}
.box-card2{
  margin-top: 10px;
}
.watch{
  margin: 10px 0;
}
.bold{
  font-weight: bold;
}
.el-card__header{
  padding: 9px 20px !important;
}
.required::before{
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.el-button.is-circle{
  padding: 5px !important;
}
.btnall{
  margin: 17px auto -12px auto;
  width: 230px;
}
</style>
